package com.gy.room;



import java.security.KeyStore.TrustedCertificateEntry;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;
import java.util.Vector;

import com.alibaba.fastjson.JSON;

import message.DeskMessage;
import message.MoveMessage;
import message.PutWritBallMessage;
import message.SetColorMessage;
import message.ShootEndMessage;
import message.ShootMessage;
import message.extErrorMessage;
import message.faceMessage;
import message.reslutMessage;
import messageControl.MessageAction;
import messageControl.ProtocolEnum;
import messageControl.userStatesEnum;



/***
 * 鎴块棿绫� 创建加入房间
 * 
 * @author gengyu
 */
public class AbstractRoom {

	// 房间list
	public Vector<clientPlayInfo> playerList = new Vector<>();

    public boolean isStart=false;
	protected int id;// 房间ID
	int shootID =-1;
	//1.开局白 2.自由白 3击球
	int shootType=-1;
	
	int round=-1;
	
	int shootOneColorId=-1;
	int shootTwoColorId=-1;
	
	String ballPoint;
	//记录玩家的射击的时间
	float shootCuntDownTime=-1;
	String reslutMessage;
	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}
	
	
	public int chooseFisrt()
	{
		Random r = new Random();
	    int n = r.nextInt(100);
	    int m ; //随机数字
	    if(n<50){
	    	
	    	return playerList.get(0).getUserId();
	    }
	    else
	    {
	  	return playerList.get(1).getUserId();
	    	
	    }
	    	
	}
	public void startGame()
	{
		
		
		
		if(isStart)
		{
			System.out.println("!!!!!!!!!--startGame is start!!---"+id);
			return;
		}
		InitGame();
		Iterator<clientPlayInfo> it = playerList.iterator();
		while (it.hasNext()) {
			clientPlayInfo usrtmp = (clientPlayInfo) it.next();
			usrtmp.setRoomId(id);
		}
		
//		shootID=chooseFisrt();
//		shootType=1;
//		isStart=true;
//		round=1;
		
		broakcastDeskInfoStart();
	}
	public void InitGame()
	{
		shootCuntDownTime=-1;
		shootID=chooseFisrt();
		//1.开局白 2.自由白 3击球
		shootType=1;
		
		isStart=true;
		round=1;
	

		//记录玩家的射击的时间
		shootCuntDownTime=System.currentTimeMillis();
		reslutMessage="";
	}
	
	 /*关闭房间*/
//	   public void closeRooms()
//	   {
//			Iterator<clientPlayInfo> it = playerList.iterator();
//			while (it.hasNext()) {
//				clientPlayInfo usrtmp = (clientPlayInfo) it.next();
//				userManager.getInstance().resetRoomState();
//
//		   
//		   }
//		   //将玩家状态清空
//		   
//		   waitringlist.clear();
//		   
//	   }
	public DeskMessage  getDeskUserInfo()
	{
		if(playerList.size()<playMaxNum)
			return null;
		clientPlayInfo playerOne=playerList.get(0);
		clientPlayInfo playerTwo;
//		clientPlayInfo playerTwo=playerList.get(1);
		if(playerList.get(1)!=null)
		playerTwo=playerList.get(1);
		else
		playerTwo=playerList.get(0);
		DeskMessage dk=new DeskMessage();
		dk.setRoomId(id);
		dk.setRounds(round);
		dk.setUserIdOne(playerOne.getUserId());
		dk.setSexOne(playerOne.getSex());
		dk.setHeadUrlOne(playerOne.getHeadUrl());
		dk.setNameOne(playerOne.getName());
		
		dk.setUserIdTwo(playerTwo.getUserId());
		dk.setSexTwo(playerTwo.getSex());
		dk.setHeadUrlTwo(playerTwo.getHeadUrl());
		dk.setNameTwo(playerTwo.getName());
		
		dk.setServeOrder(shootID);
		dk.setServerOrderType(shootType);
		dk.setSuc(true);
		return dk;
	}
	/*传递座子上所有的球的情况，以及其他人打过球的情况*/
	public void broakcastDeskInfoStart()
	{
		DeskMessage tmp=getDeskUserInfo();
		tmp.setMsgId(1102);
		MessageAction.getInstance().sendMessage(playerList.get(0).ctx, JSON.toJSONString(tmp));
		
		if(playerList.get(1)!=null)
		{
			MessageAction.getInstance().sendMessage(playerList.get(1).ctx, JSON.toJSONString(tmp));
		}
		//
	}
	
	
	//重置整个房间的状态
	public void resetRoom()
	{
		playerList.clear();
		shootCuntDownTime=-1;
		 shootID =-1;
		//1.开局白 2.自由白 3击球
		 shootType=-1;
		
		 round=-1;
		
		 shootOneColorId=-1;
		 shootTwoColorId=-1;
		
		 ballPoint="";
		//记录玩家的射击的时间
		shootCuntDownTime=-1;
		reslutMessage="";
		isStart=false;
	}
	
	//广播游戏中的射击消息
	public void broakcastShootInfo(ShootMessage msg)
	{
		
		int tmpUserId=msg.getUserId();
		if(!isPlayerIn(tmpUserId))
		{
			 System.out.println("!isPlayerIn");
			return;	
		}
		recordShootTime();
		shootID=tmpUserId;
		shootType=3;
		shootCuntDownTime=System.currentTimeMillis();
		Iterator<clientPlayInfo> it = playerList.iterator();
		while (it.hasNext()) {
			clientPlayInfo usrtmp = (clientPlayInfo) it.next();
			if(usrtmp.getUserId()!=tmpUserId)
			{
				msg.setMsgId(1103);
				MessageAction.getInstance().sendMessage(usrtmp.getCtx(), JSON.toJSONString(msg));
			}
			
		}
		
	}
	public void broakcastShootTimeoutInfo()
	{
		
		extErrorMessage msg=new extErrorMessage();
		msg.setErrorcontext("shoot timeout");
		msg.setMsgId(101);
		msg.setShootID(shootID);
		msg.setShootType(shootType);
		msg.setLostUserId(-1);
		Iterator<clientPlayInfo> it = playerList.iterator();
		while (it.hasNext()) {
			clientPlayInfo usrtmp = (clientPlayInfo) it.next();
			
			
				MessageAction.getInstance().sendMessage(usrtmp.getCtx(), JSON.toJSONString(msg));
		
			
		}
	}
	
	public void broakcastShootGameoutInfo(int userid)
	{
		
		extErrorMessage msg=new extErrorMessage();
		msg.setErrorcontext("shoot timeout");
		msg.setMsgId(101);
		msg.setShootID(shootID);
		msg.setShootType(shootType);
		msg.setLostUserId(userid);
		Iterator<clientPlayInfo> it = playerList.iterator();
		while (it.hasNext()) {
			clientPlayInfo usrtmp = (clientPlayInfo) it.next();
			
			
				MessageAction.getInstance().sendMessage(usrtmp.getCtx(), JSON.toJSONString(msg));
		
			
		}
	}
	public void recordShootTime()
	{
		shootCuntDownTime=System.currentTimeMillis();
	}
	public void broakcastShootEnd(ShootEndMessage msg)
	{
		int tmpUserId=msg.getUserId();
		if(!isPlayerIn(tmpUserId))
		{
			 System.out.println("!isPlayerIn");
			return;	
		}
		shootID=msg.getServeOrder();
		shootType=msg.getServerOrderType();
		ballPoint=msg.getBallPoint();
		Iterator<clientPlayInfo> it = playerList.iterator();
		recordShootTime();
		while (it.hasNext()) {
			clientPlayInfo usrtmp = (clientPlayInfo) it.next();
		//	if(usrtmp.getUserId()!=tmpUserId)
			{
				msg.setMsgId(ProtocolEnum.S2C_ShootEnd);
				MessageAction.getInstance().sendMessage(usrtmp.getCtx(), JSON.toJSONString(msg));
			}
			
		}
	}
	public void broakcastface(faceMessage msg,String str)
	{
		int tmpUserId=msg.getUserId();
		if(!isPlayerIn(tmpUserId))
		{
			 System.out.println("!isPlayerIn");
			return;	
		}

		Iterator<clientPlayInfo> it = playerList.iterator();
		while (it.hasNext()) {
			clientPlayInfo usrtmp = (clientPlayInfo) it.next();
			if(usrtmp.getUserId()!=tmpUserId)
			{
				msg.setMsgId(ProtocolEnum.S2C_Facer);
				MessageAction.getInstance().sendMessage(usrtmp.getCtx(), JSON.toJSONString(msg));
			}
		}
			
	}
	public void broakcastGameOverInfo(reslutMessage msg)
	{
		int tmpUserId=msg.getUserId();
		if(!isPlayerIn(tmpUserId))
		{
			 System.out.println("!isPlayerIn");
			return;	
		}

		Iterator<clientPlayInfo> it = playerList.iterator();
		while (it.hasNext()) {
	clientPlayInfo usrtmp = (clientPlayInfo) it.next();
		//	if(usrtmp.getUserId()!=tmpUserId)
			{
				msg.setMsgId(ProtocolEnum.S2C_GameOver);
				MessageAction.getInstance().sendMessage(usrtmp.getCtx(), JSON.toJSONString(msg));
			}
		}
			
		
		resetRoom();
	}
	public void broakcastPutBall(PutWritBallMessage msg)
	{
		int tmpUserId=msg.getUserId();
		if(!isPlayerIn(tmpUserId))
		{
			 System.out.println("!isPlayerIn");
			return;	
		}

		Iterator<clientPlayInfo> it = playerList.iterator();
		while (it.hasNext()) {
			clientPlayInfo usrtmp = (clientPlayInfo) it.next();
			if(usrtmp.getUserId()!=tmpUserId)
			{
				msg.setMsgId(ProtocolEnum.S2C_PutWriteBall);
				MessageAction.getInstance().sendMessage(usrtmp.getCtx(), JSON.toJSONString(msg));
			}
			
		}
	}
	public void broakcastSetColor(SetColorMessage msg)
	{
		int tmpUserId=msg.getUserId();
		if(!isPlayerIn(tmpUserId))
		{
			 System.out.println("!isPlayerIn");
			return;	
		}
		shootOneColorId=msg.getColorOne();
		 shootTwoColorId=msg.getColorTwo();
		Iterator<clientPlayInfo> it = playerList.iterator();
		while (it.hasNext()) {
			clientPlayInfo usrtmp = (clientPlayInfo) it.next();
			//if(usrtmp.getUserId()!=tmpUserId)
			{
				msg.setMsgId(ProtocolEnum.S2C_GetShootColor);
				MessageAction.getInstance().sendMessage(usrtmp.getCtx(), JSON.toJSONString(msg));
			}
			
		}
	}
	public void broakcastMoveInfo(MoveMessage msg )
	{
		int tmpUserId=msg.getUserId();
		if(!isPlayerIn(tmpUserId))
		{
			 System.out.println("!isPlayerIn");
			return;	
		}
			
		Iterator<clientPlayInfo> it = playerList.iterator();
		while (it.hasNext()) {
			clientPlayInfo usrtmp = (clientPlayInfo) it.next();
			if(usrtmp.getUserId()!=tmpUserId)
			{
				msg.setMsgId(1104);
				MessageAction.getInstance().sendMessage(usrtmp.getCtx(), JSON.toJSONString(msg));
			}
			
		}
	}
	
	public boolean isPlayerIn(int playerid)
	{

		
		Iterator<clientPlayInfo> it = playerList.iterator();
		while (it.hasNext()) {
			clientPlayInfo usrtmp = (clientPlayInfo) it.next();
			if(usrtmp.getUserId()==playerid)
			{
				
			   return true;
			}
			
		}
		return false;
	}
	public boolean isFull() {
		if(playerList.size()>=playMaxNum||isStart)
			return true;
		return false;
		
	}
	public void enterRoom(clientPlayInfo player)
	{
		player.init();

		playerList.add(player);
		player.setStates(userStatesEnum.inRoom);
		//如果房间满了，还没有开始则开始游戏
		if(isFull()&&!isStart)
		{
			startGame();
		}
	}
	//定时刷新房间的数据
	public void update()
	{
		
		//先判断玩家是否有掉线
		checkUserLeaveLine();
		//如果未超时，则判是否超时
		if(!isStart)
		{
			checkUserTimeOut();
			
		}
		//判断顽疾击打是否超时
		else
		{
			checkUserShootTime();
		}
	}
	public void checkUserShootTime()
	{
		if(System.currentTimeMillis() - shootCuntDownTime > 10)
		{
			broakcastShootTimeoutInfo();
			shootCuntDownTime=System.currentTimeMillis();
		}
	}
	/*判断玩家是否离线，如果离线则直接判负*/
	public void checkUserLeaveLine()
	{
		Iterator<clientPlayInfo> it = playerList.iterator();
		while (it.hasNext()) {
			clientPlayInfo usrtmp = (clientPlayInfo) it.next();
			if(usrtmp.getStates()!=userStatesEnum.inRoom)
			{
				
				 
				 if(usrtmp.getStates()==userStatesEnum.leavingLine)
				 {
					 if(usrtmp.getDisconnetTime()==-1)
					 {
						 System.out.println("(usrtmp.getDisconnetTime()");
						 usrtmp.setDisconnetTime( System.currentTimeMillis());
						 
					 }
					 else
					 {
						 if(System.currentTimeMillis() - usrtmp.getStartWaittingTime() > 30)
						 {
							 //房间结束，判断为另外一个人成功
						 }
					 }
				 }
				 else
				 {
					 System.out.println("usrtmp state fail"+usrtmp.getStates());
				 }
			}
			
			
			
		}
	}
	
	public void checkUserTimeOut()
	{
		Iterator<clientPlayInfo> it = playerList.iterator();
		while (it.hasNext()) {
			clientPlayInfo usrtmp = (clientPlayInfo) it.next();
			if( System.currentTimeMillis() - usrtmp.getStartWaittingTime() > 30)
			{
				DeskMessage tmp=getDeskUserInfo();
				if(tmp!=null)
				{
				tmp.setMsgId(1102);
				tmp.setSuc(false);
				MessageAction.getInstance().sendMessage(usrtmp.getCtx(), JSON.toJSONString(tmp));
				it.remove();
				}
			}
			
		}
	}


	
	




	public AbstractRoom() {
		// 获取随机生成的房间Id，设置类型
	
	}
	
	protected boolean isStartGame = false;



	public void setStartGame(boolean isStartGame) {
		this.isStartGame = isStartGame;
	}



	public int playMaxNum = 2; // 游戏人数





}
